package com.blogsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blogsystem.entity.Article;
import com.blogsystem.entity.Category;
import com.blogsystem.entity.Comment;
import com.blogsystem.entity.User;
import com.blogsystem.service.ArticleService;
import com.blogsystem.service.CategoryService;
import com.blogsystem.service.CommentService;
import com.blogsystem.service.UserService;
// 添加方法级安全注解支持
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder; // 引入 PasswordEncoder
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章管理控制器
 */
@Controller
@RequestMapping("/api/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserService userService; // 确保UserService已注入

    @Autowired
    private CommentService commentService; // 注入评论服务

    @Autowired
    private PasswordEncoder passwordEncoder; // 注入密码编码器
    /**
     * 发布文章
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public String publishArticle(@ModelAttribute Article article,
                                @RequestParam Integer categoryId,
                                Authentication authentication,
                                RedirectAttributes redirectAttributes,
                                @RequestParam(required = false) Integer draftId) {
        // 通过分类ID获取分类信息
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            article.setCategoryId(category.getCategoryId());
        }

        // 设置文章状态（确保从表单获取的状态值有效）
        if (article.getStatus() == null || 
            (!article.getStatus().equals(0) && !article.getStatus().equals(2))) {
            article.setStatus(2); // 默认设置为发布状态
        }

        // 处理草稿保存
        if (draftId != null && "0".equals(article.getStatus())) {
            Article existingDraft = articleService.getById(draftId);
            if (existingDraft != null && isCurrentUserAuthorOfArticle(existingDraft)) {
                article.setArticleId(draftId); // 保留原有ID
            }
        }

        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof org.springframework.security.core.userdetails.UserDetails userDetails) {
                String username = userDetails.getUsername();
                User user = userService.findByUsername(username);
                if (user != null) {
                    article.setUserId(user.getUserId());
                }
            }
        }

        article.setCreateTime(java.time.LocalDateTime.now());

        System.out.println("发布文章：" + article);
        boolean success = articleService.saveOrUpdate(article);
        if (success) {
            redirectAttributes.addFlashAttribute("success", true);
            redirectAttributes.addFlashAttribute("status", article.getStatus());
        } else {
            redirectAttributes.addFlashAttribute("success", false);
        }
        return "redirect:/user/center";
    }
    /**
     * 打开发布文章页面
     */
    @GetMapping("/newArticle")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 允许普通用户和管理员访问
    public String showNewArticleForm(@RequestParam(required = false) Integer draftId, Model model) {
        if (draftId != null) {
            Article draft = articleService.getById(draftId);
            if (draft != null && isCurrentUserAuthorOfArticle(draft)) {
                model.addAttribute("article", draft);
                model.addAttribute("isDraft", true);
                model.addAttribute("draftId", draftId);
            }
        } else {
            model.addAttribute("article", new Article());
        }
        
        model.addAttribute("categories", categoryService.list());
        return "publish_article";
    }
    /**
     * 获取当前用户的草稿文章
     */
    @GetMapping("/drafts")
    public List<Article> getDraftArticles(org.springframework.security.core.Authentication authentication) {
        if (authentication != null && authentication.isAuthenticated()) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
                String username = ((org.springframework.security.core.userdetails.UserDetails) principal).getUsername();
                return articleService.getDraftArticlesByUsername(username);
            }
        }
        return Collections.emptyList();
    }

    /**
     * 分页查询文章列表（支持分类筛选）
     * @param pageNum 当前页码，默认第一页
     * @param categoryId 分类ID，可选
     * @return 分页数据 + 分类列表
     */
    @GetMapping
    public String listArticles(@RequestParam(defaultValue = "1") int pageNum,
                             @RequestParam(required = false) Integer categoryId,
                             Model model) {
        // 构建分页对象（每页 5 条）
        Page<Article> page = new Page<>(pageNum, 5);

        // 构建查询条件
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }

        // 查询分页数据
        Page<Article> articlePage = articleService.page(page, queryWrapper);

        // 准备返回结果
        model.addAttribute("articles", articlePage.getRecords());
        model.addAttribute("totalPages", articlePage.getPages());
        model.addAttribute("currentPage", pageNum);
        model.addAttribute("hasPrevious", pageNum > 1);
        model.addAttribute("hasNext", pageNum < articlePage.getPages());
        model.addAttribute("categories", categoryService.list());
        model.addAttribute("categoryId", categoryId);
        return "article_list";
    }

    /**
     * 查看文章详情
     */
    @GetMapping("/{id}")
    public String viewArticle(@PathVariable Integer id, Model model) {
        Article article = articleService.getById(id);
        if (article == null) {
            return "error/404"; // 如果找不到文章，返回 404 页面
        }
        model.addAttribute("article", article);
        model.addAttribute("comments", commentService.getCommentsByArticleId(id));
        model.addAttribute("categories", categoryService.list());
        return "article_detail";
    }

    /**
     * 获取文章详情 API 接口
     */
    @GetMapping("/{id}/details")
    public ResponseEntity<Article> getArticleById(@PathVariable Integer id) {
        Article article = articleService.getById(id);
        if (article == null) {
            return ResponseEntity.notFound().build();
        }
        

        return ResponseEntity.ok(article);
    }
    
    /**
     * 撤回文章（将状态改为草稿）
     */
    @PostMapping("/retract/{id}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public ResponseEntity<Boolean> retractArticle(@PathVariable Integer id) {
        Article article = articleService.getById(id);
        if (article == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 确保用户只能撤回自己的文章
        if (!isCurrentUserAuthorOfArticle(article)) {
            return ResponseEntity.status(403).body(false);
        }
        
        // 更新文章状态为草稿
        article.setStatus(0); // 草稿状态
        boolean success = articleService.updateById(article);
        
        return ResponseEntity.ok(success);
    }
    
    /**
     * 删除文章
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public ResponseEntity<Boolean> deleteArticle(@PathVariable Integer id) {
        Article article = articleService.getById(id);
        if (article == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 确保用户只能删除自己的文章
        if (!isCurrentUserAuthorOfArticle(article)) {
            return ResponseEntity.status(403).body(false);
        }
        
        boolean success = articleService.removeById(id);
        return ResponseEntity.ok(success);
    }
    
    /**
     * 删除评论
     */
    @DeleteMapping("/comments/{id}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public ResponseEntity<Boolean> deleteComment(@PathVariable Integer id) {
        Comment comment = commentService.getById(id);
        if (comment == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 确保用户只能删除自己的评论
        if (!isCurrentUserAuthorOfComment(comment)) {
            return ResponseEntity.status(403).body(false);
        }
        
        boolean success = commentService.removeById(id);
        return ResponseEntity.ok(success);
    }
    
    /**
     * 检查当前用户是否是文章的作者
     */
    private boolean isCurrentUserAuthorOfArticle(Article article) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        String currentUsername = authentication.getName();
        User user = userService.findByUsername(currentUsername);
        return user != null && user.getUserId().equals(article.getUserId());
    }
    
    /**
     * 检查当前用户是否是评论的作者
     */
    private boolean isCurrentUserAuthorOfComment(Comment comment) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }
        
        String currentUsername = authentication.getName();
        User user = userService.findByUsername(currentUsername);
        return user != null && user.getUserId().equals(comment.getUserId());
    }
    
    /**
     * 获取当前用户的所有文章
     */
    @GetMapping("/user/articles")
    public ResponseEntity<List<Article>> getUserArticles() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body(null);
        }
        
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        List<Article> articles = articleService.getAllArticlesByUserId(user.getUserId());
        return ResponseEntity.ok(articles);
    }
    
    /**
     * 获取当前用户的文章详情
     */
    @GetMapping("/user/articles/{id}")
    public ResponseEntity<Article> getUserArticleById(@PathVariable Integer id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body(null);
        }
        
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        Article article = articleService.getById(id);
        if (article == null || !article.getUserId().equals(user.getUserId())) {
            return ResponseEntity.status(403).body(null);
        }
        
        return ResponseEntity.ok(article);
    }
    
    /**
     * 修改文章
     */
    @PutMapping("/{id}")
    public String updateArticle(@PathVariable Integer id, @RequestBody Article article) {
        article.setArticleId(id); // 设置主键
        boolean success = articleService.updateById(article);
        return success ? "修改成功" : "修改失败";
    }


    /**
     * 文章审核（管理员）
     */
    @PostMapping("/audit/{id}")
    public String auditArticle(@PathVariable Integer id) {
        // 假设审核逻辑是更新状态字段
        Article article = articleService.getById(id);
        article.setStatus(1); // 假设 1 表示已审核
        boolean success = articleService.updateById(article);
        return success ? "审核成功" : "审核失败";
    }

    /**
     * 批量操作（如批量删除、批量修改状态）
     */
    @PostMapping("/batch")
    public String batchOperate(@RequestBody Map<String, Object> payload) {
        String action = (String) payload.get("action");
        @SuppressWarnings("unchecked")
        java.util.List<Integer> ids = (java.util.List<Integer>) payload.get("ids");

        switch (action) {
            case "delete":
                articleService.removeByIds(ids);
                return "批量删除成功";
            case "publish":
                // 示例：批量发布
                for (Integer id : ids) {
                    Article article = articleService.getById(id);
                    article.setStatus(1); // 已发布
                    articleService.updateById(article);
                }
                return "批量发布成功";
            default:
                return "不支持的操作";
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 明确要求用户或管理员角色
    public ResponseEntity<Boolean> changePassword(@RequestBody Map<String, String> payload) {
        String currentPassword = payload.get("currentPassword");
        String newPassword = payload.get("newPassword");
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(401).body(false);
        }
        
        String username = authentication.getName();
        User user = userService.findByUsername(username);
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 验证当前密码
        if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
            return ResponseEntity.status(401).body(false);
        }
        
        // 更新新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        boolean success = userService.updateById(user);
        
        return ResponseEntity.ok(success);
    }
}
